<template>
  <div class="goods-container">
    <Card :data="data" :isdetails="true" />
    <Other
      ref="other"
      :userData="userData"
      :data="data"
      :ispurchase="ispurchase"
      @shop="shop"
    />
    <Comment :id="id" :userData="userData" @refresh="refresh" />
    <el-dialog title="租借详情" :visible.sync="dialogVisible" width="80%">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="租借时间">
          <el-input v-model="form.time"
            ><template slot="append">天</template></el-input
          >
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { query, addGoodclick, updateGood, addOrder } from "@/api/goodslist";
import { transformTimestamp } from "@/tools/utils";
import Card from "@/components/Card.vue";
import Other from "./components/Other.vue";
import Comment from "./components/Comment.vue";

export default {
  name: "goods",
  data() {
    return {
      data: {},
      ispurchase: false,
      userData: {},
      id: "",
      dialogVisible: false,
      form: {
        time: 1,
      },
    };
  },
  components: {
    Card,
    Other,
    Comment,
  },
  watch: {},
  created() {},
  mounted() {
    const { id } = this.$route.query;
    this.id = id;
    this.userData = JSON.parse(localStorage.getItem("userData")) || undefined;
    this.addGoodclick(id);
    this.getData(id);
  },
  methods: {
    submit() {
      addOrder({
        goods_id: this.id,
        buyer_id: this.userData.id,
        seller_id: this.data.user_id,
        days: this.form.time,
      }).then(() => {
        this.getData(this.id);
        this.dialogVisible = false;
      });
    },
    addGoodclick(id) {
      addGoodclick({ id: id });
    },
    shop() {
      this.dialogVisible = true;
    },
    refresh() {
      this.$refs.other.init();
    },
    getData(val) {
      query({
        currPage: 1,
        pageSize: 10,
        id: val,
      })
        .then((res) => {
          if (this.userData) {
            if (this.userData.id != res.data.user_id && res.data.state == 2) {
              this.ispurchase = true;
            }
          }
          this.data = res.data.map((item) => {
            return {
              ...item,
              release_time: transformTimestamp(item.release_time),
            };
          })[0];
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss">
@import "./index.scss";
</style>
